package spring.cloud.tasks.executor.listener.config;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import spring.cloud.tasks.executor.listener.TreeCacheListener;
import spring.cloud.tasks.executor.utils.log.LogUtils;

@Slf4j
@Setter
@Getter
class EnabledOrDisableTaskListener extends TreeCacheListener {
    private final ConfigurationListenerHolder configurationListener;

    public EnabledOrDisableTaskListener(ConfigurationListenerHolder configurationListener) {
        this.configurationListener = configurationListener;
    }

    /**
     * if it's a msgJob, job should go down and up as the enabled value changed from false to true.<br>
     * therefor, we don't care about whether the channel/queue name is changed.
     */
    @Override
    protected void dataChanged(CuratorFramework curatorFramework, String path, TreeCacheEvent treeCacheEvent) {
        if (configurationListener.isShutdown) {
            return;
        }
        if (ConfigurationNode.isEnabledPath(configurationListener.taskId, path) && TreeCacheEvent.Type.NODE_UPDATED == treeCacheEvent.getType()) {
            Boolean enabled = Boolean.valueOf(new String(treeCacheEvent.getData().getData()));
            LogUtils.info(log, configurationListener.taskId, "{} 's enabled change to {}", configurationListener.taskId, enabled);
            configurationListener.taskConfiguration.reloadTaskConfiguration();
            if (enabled) {
                if (!isJobNotNull()) {
                    return;
                }

                if (configurationListener.taskExecutor.getReportService() != null) {
                    configurationListener.taskExecutor.getReportService().clearInfoMap();
                }
                configurationListener.failoverService.removeFailoverFlag();
                configurationListener.taskExecutor.getTaskExecuteEngine().enableTask();
                configurationListener.taskConfigurationService.notifyTaskEnabledIfNecessary();
            } else {
                if (!isJobNotNull()) {
                    return;
                }

                configurationListener.taskExecutor.getTaskExecuteEngine().disableTask();
                configurationListener.failoverService.removeFailoverFlag(); // clear failover info when disable job.
                configurationListener.taskConfigurationService.notifyTaskDisabled();
            }
        }
    }

    private boolean isJobNotNull() {
        return configurationListener.taskExecutor != null && configurationListener.taskExecutor.getTaskExecuteEngine() != null;
    }
}
